package com.eportal.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.dao.TCommodityEntityMapper;
import com.eportal.dao.TCommodityPriceEntityMapper;
import com.eportal.dao.TCommodityPropertyEntityMapper;
import com.eportal.domain.Sysopt;
import com.eportal.entity.TCommodityEntity;
import com.eportal.entity.TCommodityPriceEntity;
import com.eportal.entity.TCommodityPropertyEntity;
import com.eportal.params.background.mall.Tcommodity.CommodityParam;
import com.eportal.params.background.mall.Tcommodity.CommodityParamList;
import com.eportal.service.*;
import com.eportal.util.ValidateUtil;
import com.eportal.vo.controller.background.commodity.QueryStatusNumsVO;
import com.framework.jqgrid.JqGridPager;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品管理业务逻辑接口实现
 */
@Service
public class TCommodityServiceImpl extends BaseServiceImpl<TCommodityEntity> implements TCommodityService {

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger logger = LoggerFactory.getLogger(CInstallUnitServiceImpl.class.getName());
	@Resource(name="dao")
	private BaseDAO dao;

	@Resource
	private TCommodityEntityMapper tCommodityDao;

	@Autowired
    private TUsersService tUsersService;
    @Autowired
    private TCommunityService tCommunityService;
    @Autowired
    private TKeysService tKeysService;
    @Autowired
    private UserWalletService userWalletService;

    @Autowired
    private TCommodityPriceEntityMapper tCommodityPriceDao;
    @Autowired
    private TCommodityPropertyEntityMapper tCommodityPropertyDao;


    public com.eportal.domain.TCommodity get(Long sid) {
        return (com.eportal.domain.TCommodity) dao.getById(com.eportal.domain.TCommodity.class, sid);
    }


    public void updateObject(Object entity) throws Exception {
    	dao.update(entity);
	}



	public Object getObjectHql(String name,String where) {
		StringBuffer sb = new StringBuffer("from ");
		sb.append(name);
		sb.append(" where ");
		sb.append(where);
	     return  dao.loadObject(sb.toString());
	}






	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }


	@Override
	public List<Map<String, Object> > listView(JqGridPager jqGridPager) {
		String sql = "select t1.sid,t1.cname,t1.stock,t1.photo,t1.attr_photo,t2.price1 from t_commodity t1,t_commodity_attr t2 ";
		return dao.query(sql, jqGridPager);
	}

	@Override
	public List<Map<String, Object> > logList(JqGridPager jqGridPager) {
		String sql = "select (select ta.agtname from t02_agtent ta where ta.agtcode = t1.agtcode) agtname," +
				"(select tc.communityname from t03_community tc where tc.sid = t1.communityid) comname," +
				"(select tl.install_lock_name from t05_locks tl where tl.pid = t3.pid) lockname," +
				"(select tu.tel from t04_users tu where tu.userid = t3.userid) tel," +
				"t3.pid,t1.rname,t3.remoney,to_char(t3.retime,'YYYY-MM-DD HH24:MI:SS') retime " +
				"from t_redenvmain t1,t_redenvdetail t2,t_redenvreceivelog t3 ";
		return dao.query(sql, jqGridPager);
	}

	@Override
	public Map<String, Object> offMethod(Long sid, Sysopt opt) throws Exception {
		return null;
	}

	@Override
	public List<Map<String, Object>> cmdDetail(Long sid) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("select t1.sid,t1.cname,t1.stock,t1.remainstock,t1.photo,t1.attr_photo,t2.startnumber1,t2.endnumber1,t2.price1,");
		sb.append("t2.startnumber2,t2.endnumber2,t2.price2,t2.startnumber3,t2.endnumber3,t2.price3,");
		sb.append("t2.startnumber4,t2.endnumber4,t2.price4,t2.attributename,t2.attributevalue");
		sb.append(" from t_commodity t1,t_commodity_attr t2 ");
		sb.append("where t1.sid = t2.cid and t1.sid="+sid);
		return dao.queryBySql(sb.toString());
	}

	@Override
	public Map<String, Object> addRedEnv(Sysopt opt, String rName, BigDecimal Amount, int totalNum, int reTimes, String effectiveDate, String period1, String period2, String isAllday,
			 String isSendAll, String agentCodes, String communityIds, String buildingIds, String unitIds, String roomIds, String mainReType, String cUrl, String adPicture, String reqPreUrl) {
		return null;
	}



	@Override
	public List<Map<String, String>> listBySql(String hql) {
		return dao.queryBySql(hql);
	}


	public List<Map<String, Object>> getRoom(String unitId, String roomNo) {
		StringBuilder sql = new StringBuilder("select t.sid,t.room_no as roomno,t.floor_no as floorno from T035_ROOM t where t.unit_id='");
		sql.append(unitId);
		sql.append("' and t.room_no ='");
		sql.append(roomNo);
		sql.append("'");
		return dao.queryBySql(sql.toString());
	}

	@Override
	public List<Map<String, Object>> queryBySql(String unit, String budingid) {
		StringBuffer sql = new StringBuffer();

		sql.append("select t.userid,u.tel as usertel,u.auname as username from t04_users_community t  left join t04_users u on t.userid=u.userid where ");
		if (StringUtils.isNotBlank(unit)) {
			sql.append(" t.installunitid in(");
			sql.append(unit);
			sql.append(")");
		}else{
			sql.append(" t.cbuildingId=");
			sql.append(budingid);
		}
		return dao.queryBySql(sql.toString());
	}


	//激活红包
	@Override
	public Map<String, Object> activeRedenv(String redEnvId) {
		// TODO Auto-generated method stub
    	result = new HashMap<String, Object>();
		List<Map<String, Object>> list = dao.queryBySql("select PSTATE from t_pay_order where ORDER_RELATE_ID = '"+redEnvId+"'");
		if(list.size()==0){
			 result.put("code", 0);
	         result.put("msg", "没有找到相应的红包订单");
	         return result;
		}else{
			if("0".equals(String.valueOf(list.get(0).get("PSTATE")))){
				 String updateSql = "update t_redenvdetail t set t.envstatus = '1' where t.remainid ="+redEnvId;
				 dao.updateBySql(updateSql);
				 result.put("code", 1);
		         result.put("msg", "操作成功");
			}else{
				 result.put("code", 0);
		         result.put("msg", "订单未支付");
		         return result;
			}
		}
        return result;
	}


	@Override
	public String getOrderBatchNummber() throws Exception{
		// TODO Auto-generated method stub
		String sql = "select substr(SEQ_ORDER_BATCHNUMBER.nextval,-4) BATCHNUMBER from dual";
		List<Map> list = dao.queryBySql(sql);
		return String.valueOf(list.get(0).get("BATCHNUMBER"));
	}


	/**
	 * 分页查询
	 *
	 * @param pageEntity 分页对象
	 * @param optId   当前用户id
	 * @param ownerId 当前用户所属id
	 * @author Saber
	 * @Date 2017/7/14 下午12:39
	 */
	@Override
	public PageInfo<TCommodityEntity> queryForPage(PageEntity pageEntity,CommodityParamList commodityParamList,Long optId,String ownerId) {

		//调用分页
		PageHelper.startPage(pageEntity.getPageNo(),pageEntity.getPageSize());

		List<TCommodityEntity> list = tCommodityDao.queryForList(commodityParamList,optId,ownerId);
		return new PageInfo<>(list);
	}

	/**
	 * 查询商品各状态数量
	 *
	 * @param optId   当前用户id
	 * @param ownerId 当前用户所属id
	 * @return
	 * @author Saber
	 * @Date 2017/7/24 下午1:06
	 */
	@Override
	public QueryStatusNumsVO queryStatusNums(Long optId, String ownerId) {
		return tCommodityDao.queryStatusNums(optId,ownerId);
	}

	/**
     * 商品添加
     * @Author Saber
     * @Date 2017/7/10 下午1:34
     * @param param     请求参数
     * @param ownerId   当前用户所属id
     * @param optId     当前用户id
     */
    @LogAnnotation(operateDescribe="商品保存")
	@Transactional
    @Override
	public JSONObject commodityAdd(CommodityParam param,Long optId,String ownerId) throws Exception {
		JSONObject json = new JSONObject();
		//验证参数
		String msg = ValidateUtil.validate(param);
		if (org.apache.commons.lang3.StringUtils.isNotBlank(msg)) {

			//基本信息
			TCommodityEntity tCommodity = new TCommodityEntity();
			tCommodity.setCname(param.getCname());//商品名称
			tCommodity.setStock(param.getStock());//库存（原始值 消费的时候此值不变）
			tCommodity.setRemainstock(param.getStock());//剩余库存）
			if(org.apache.commons.lang3.StringUtils.isBlank(param.getPhoto())){
				json.put("code",0);
				json.put("msg","图片不能为空");
				return json;
			}
			//大图
			tCommodity.setPhoto(param.getPhoto());

			//校验小图数量
			String[] attrPhotos = param.getAttrPhoto().split(",");
			StringBuffer attrPhotoUrls = new StringBuffer();
			if(attrPhotos==null){
				json.put("code",0);
				json.put("msg", "图片不能为空");
				return json;
			}else if(attrPhotos.length<4){
				json.put("code",0);
				json.put("msg","图片数量不能小于4张");
				return json;
			}
			tCommodity.setAttrPhoto(attrPhotoUrls.toString());//商品详情小图

			tCommodity.setStatus("0");//状态 0/1/2 :新增/上架/下架
			tCommodity.setOptid(optId.toString()); //操作人id
			tCommodity.setOwnerid(ownerId);

			//保存
			if(tCommodityDao.insertSelective(tCommodity)==0){
				throw new SQLException("商品添加异常");
			}

			//商品价格
			List<TCommodityPriceEntity> priceList = JSONArray.parseArray(param.getPriceJSONStr(), TCommodityPriceEntity.class);//json字符串转为对象
			for (TCommodityPriceEntity price : priceList){
				if(tCommodity.getSid()==null){
					json.put("code",0);
					json.put("msg","商品id为空");
					return json;
				}
				price.setCommodityId(tCommodity.getSid().toString());//回填外键
				//保存
				if(tCommodityPriceDao.insertSelective(price)==0){
					throw new RuntimeException("保存商品价格出错");
				}
			}

//            System.out.println(1/0);

			//商品属性
			List<TCommodityPropertyEntity> propertyList = JSONArray.parseArray(param.getGoodArrtibuteJSONStr(), TCommodityPropertyEntity.class);//json字符串转为对象;
			for (TCommodityPropertyEntity tCommodityProperty : propertyList) {
				if(tCommodity.getSid()==null){
					json.put("code",0);
					json.put("msg","商品id为空");
					return json;
				}
				tCommodityProperty.setCommodityId(tCommodity.getSid().toString());
				if(tCommodityPropertyDao.insertSelective(tCommodityProperty)==0){
					throw new RuntimeException("保存商品属性出错");
				}

			}

			json.put("code", 1);
			json.put("msg", "操作成功");
			json.put("data",tCommodity);
			return json;

		} else {
			json.put("code", 0);
			json.put("msg", msg);
			return json;
		}


	}


	/**
	 * 商品上架
	 *
	 * @param sIds    商品id 以,分割
	 * @param optId   当前用户id
	 * @param ownerId 当前用户所属id
	 * @return
	 * @author Saber
	 * @Date 2017/7/24 上午11:18
	 */
	@LogAnnotation(operateDescribe="商品上架")
	@Override
	public JSONObject up(String sIds, Long optId, String ownerId) {

		JSONObject json = new JSONObject();

		try {
			//上架就是更改该商品信息的状态 status
			String[] ids = sIds.split(",");
			for (String id : ids) {
				TCommodityEntity entity = new TCommodityEntity();
				entity.setSid(Long.valueOf(id));
				entity.setStatus("1");
				entity.setOptid(optId.toString());
				entity.setActivetime(new Date());
				tCommodityDao.updateByPrimaryKeySelective(entity);
			}
			json.put("code",1);
			json.put("msg","操作成功");
			json.put("data",null);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.put("code",0);
			json.put("msg","操作失败");
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 商品下架
	 *
	 * @param sIds    商品id 以,分割
	 * @param optId   当前用户id
	 * @param ownerId 当前用户所属id
	 * @return
	 * @author Saber
	 * @Date 2017/7/24 上午11:18
	 */
	@LogAnnotation(operateDescribe="商品下架")
	@Override
	public JSONObject down(String sIds, Long optId, String ownerId) {
		JSONObject json = new JSONObject();

		try {
			//上架就是更改该商品信息的状态 status
			String[] ids = sIds.split(",");
			for (String id : ids) {
				TCommodityEntity entity = new TCommodityEntity();
				entity.setSid(Long.valueOf(id));
				entity.setStatus("2");
				entity.setOptid(optId.toString());
				tCommodityDao.updateByPrimaryKeySelective(entity);
			}
			json.put("code",1);
			json.put("msg","操作成功");
			json.put("data",null);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			json.put("code",0);
			json.put("msg","操作失败");
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 商品删除
	 *
	 * @param sIds    商品id 以,分割
	 * @param optId   当前用户id
	 * @param ownerId 当前用户所属id
	 * @return
	 * @author Saber
	 * @Date 2017/7/24 上午11:18
	 */
	@Override
	public JSONObject delete(String sIds, Long optId, String ownerId) {
		return null;
	}
}
